var fs=require("fs");

function fetch_h(rr,arr,level,parent_id,maxlevels)
{
	if (level>maxlevels) return;
	if (parent_id) {
		var cnt=rr.site.sql.execute_and_fetch_one("file_folders/count",{parent_id:parent_id});
		if (cnt.cnt>20) {
			arr.push({toomany:1,level:level});
			return;
		}
	}
	var r=rr.site.models.FileFolder.List("list_level",{parent_id:parent_id});
	r.forEach(function(x) {
		if (x.name==null) x.name=x.code?x.code:("-folder "+x.id+"-");
		x.level=level;
		if (rr.fields.file_folder_id==x.id) x.active=1;
		arr.push(x);
		fetch_h(rr,arr,level+1,x.id,maxlevels);
	});
}


function repeat(v,cnt)
{
	if (cnt==0) return "";
	var r=v;
	while (cnt-- >1) r+=v;
	return r;
}

function fill_files_data(rr,file_folder_id,arr)
{
	var path=rr.F("Files","file_folder_path",file_folder_id);
	arr.forEach(function(f) {
		f.url=path+f.id+"."+f.ext;
		if (f.type_id==1 || f.type_id==2) {
			f.icon=path+f.id+"."+f.ext;
		} else {
			f.icon=this.F("Files","guess_icon",f.ext);
		}
	});
}

exports.add=[
{
	_type:"controller",
	_config_details: {	
	},
	_config: {
		path:"adminpanel/",
		name:"AdminMediaLibrary",
		admin:1,
		role_code:"files"
	},
	
	_admin_nav: [
		{section:"contents",name:"Media Library",mode:"index"}
	],

	/**
	 * Controller: AdminMediaLibrary.index 
	 * Parameters:
	 *
	 *		config.result_style typeof String	-  path, list, icons, images
	 *		config.limited typeof Boolean		- 0/1
	 *
 	 * Fields:
	 *		TODO target typeof String			- "browser", "popup"
	 *		file_folder_id typeof Integer		-
	 *		file_type_id typeof Integer			-
	 *		file_id typeof Integer				- if set, overwrites file_folder_id to folder containing given file
	 *
	 * Cookies:
	 *		MediaLibrary_result_style
	 *
	 * Returns:
	 *		HTML
	 */
	index: function(config) {
		var t=this;
		this.adminpanel.cssclass="AdminMediaLibrary-body";
		this.F("Admin","load_l10ns");
		this.preview_sizes=[];
		var i=0;
		(this.site.previews||this.system.previews).forEach(function(a) {
			t.preview_sizes.push({x:a[0],y:a[1],i:i});i++;
		});
//		t.F("Files","all_files_update_stats");
//		var target=this.fields.target||"browser";
		if (this.fields.file_id) {
			var file=this.site.models.File.Get(this.fields.file_id);
			this.fields.file_folder_id=file.file_folder_id;
		}
		this.result_style=this.fields.result_style||"list";// TODO
		if (this.fields.file_folder_id) {
			this.file_folder=this.site.models.FileFolder.Get(this.fields.file_folder_id);
			this.file_folder.FetchLocales();
		} else {
			this.file_folder={};
		}
		if (this.fields.file_folder_id) this.cfolder=this.site.models.FileFolder.Get(this.fields.file_folder_id);

		this.select_all_file_folders=undefined;

		this.file_folders_path=[];
		var pid=this.fields.file_folder_id;
		while (pid) {
			var tmpff=this.site.models.FileFolder.Get(pid);
			this.file_folders_path.unshift(tmpff);
			pid=tmpff.parent_id;
		}
		
		function get_content(folder){
			return {
				folders:	t.site.models.FileFolder.List("list_level",{parent_id:folder.id}).map(function(el){
					if (el.parent_id==folder.id) {el.is_active = 1;}
					return el;	
				}),
				files:		t.site.models.File.List("list_of_file_folder",{file_folder_id:folder.id}),
				name:		folder.name || 'Корень',
				id:			folder.id || null
			}
		}
		
		switch (this.result_style) {
			case "path":
				this.columns = [];
				this.columns.push(get_content({id:0}));
				this.file_folders_path.forEach(function(p){
					t.columns.push(get_content(p));
				});
				var fid = this.fields.file_folder_id;
				this.files = [];
				this.columns.reverse().forEach(function(el){
					t.files=t.files.concat(el.files);
					el.folders.forEach(function(f){
						if(fid && f.id==fid) f.is_open = 1;	
					});
					fid = el.id;
				});
				this.columns.reverse()[this.columns.length-1].last_one = 1;
				break;
			case "list":
			case "icons":
			case "images":
				this.file_folders_short=[];
				var maxlevels=100;
				try { maxlevels=this.site.adminpanel.medialibrary.tree_max_levels; } catch(e) {}
				fetch_h(this,this.file_folders_short,1,null,maxlevels);
				this.folders=this.site.models.FileFolder.List("list_level",{parent_id:this.fields.file_folder_id});
				this.files=this.site.models.File.List("list_of_file_folder",{file_folder_id:this.fields.file_folder_id});
//				fill_files_data(this,this.fields.file_folder_id,this.files);
				break;
		}
/*
		this.can_delete=(target=="browser")?1:0;
		this.can_check_images=(target=="browser")?1:0;
		this['target_is_'+target]=1;
//		if (target=="simpletinymce") this['target_is_tinymce']=1;
//		if (target=="simpliertinymce") this['target_is_tinymce']=1;
//		this.is_popup=(this.action.match(/^\/admin_popup-/))?1:0;


		this.files=this.site.models.File.List("list_of_file_folder",{file_folder_id:this.fields.file_folder_id});
//		this.files_count=this.site.sql.execute_and_fetch_one("files/cnt_in_group")['cnt'];
		var ff_id=this.fields.file_folder_id||0;
		this.current_file_folders=this.site.models.FileFolder.List("list_level",{parent_id:ff_id});
		this.folders_tree=[];
		this.file_folders.forEach(function(fg) {
			if (fg.id==ff_id) fg.active=1;
			t.folders_tree.push({id:fg.id,name:repeat('...',fg.level-1)+fg.name});
		});
//		var path=this.F("Files","file_folder_path",this.fields.file_folder_id);
//		var basepath=this.site.paths.html;
		this.files.forEach(function(f) {
			f.href=path+f.id+"."+f.ext;
			f.image=(f.type_id==1)?path+f.id+"-preview2."+f.ext:t.F("Files","guess_icon",f.ext);
		});
		var policy=this.F("Files","user_get_autoscale_policy","offer");
		this.autoscale=policy;
		*/
		return this.Cview();
	},

	get_folders: function() {
		return JSON.stringify(this.site.models.FileFolder.ListFK());
		//return JSON.stringify(this.site.models.FileFolder.List("list_level",{parent_id:this.fields.file_folder_id}));
	},

	/**
	 * Controller: AdminMediaLibrary.file_name_update
	 *
	 * Returns:
	 *		JSON Object
	 */
	file_name_update: function(config) {
		var f=this.site.models.File.Get(this.fields.file_id);
		var l10n_id=this.user.prefer_l10n_id || this.site.default_l10n_id;
		f.FetchLocales();
		f.l10ns[l10n_id].name=this.fields.name;
		for (var k in f.l10ns) {
			var a=f.l10ns[k].name;
			if (a===null || a===undefined || a==="") f.l10ns[k].name=this.fields.name;
		}
		f.SaveAll();
		return JSON.stringify({});
	},

	/**
	 * Controller: AdminMediaLibrary.file_folder_edit
	 *
	 * Returns:
	 *		JSON Object
	 */
	file_folder_edit: function(config) {
		var f;
		if (this.fields.id && this.fields.id!="") {
			f=this.site.models.FileFolder.Get(this.fields.id);
		} else {
			f=this.site.models.FileFolder.Create({user_cr_id:this.uid});
		}
//		f.Apply({parent_id:this.fields.parent_id,code:this.fields.code});
		var l10n_id=this.user.prefer_l10n_id || this.site.default_l10n_id;
		f.FetchLocales();
		f.ApplyAdminFields(this.fields);
//		f.l10ns[l10n_id].name=this.fields.name;
		f.SaveAll();
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.upload_file
	 */
	upload_file: function(config) {
		var l10ns={};
		for (var k in this.fields) {
			var arr=k.match(/^(\d+)__name$/);
			if (arr) l10ns[arr[1]]=this.fields[k];
		}
		var options={
			inputname:"file",
			ff_id:this.fields.file_folder_id,
//			downscale_policy:{},
			l10ns:l10ns	
		};
		var fid=this.F("Files","user_upload_file",options);
		if (!fid) throw "Could not upload file";
		if (!fid.toString().match(/^\d+$/)) throw fid;
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.upload_files
	 */
	upload_files: function(config) {
		var t=this;
		function work()
		{
			var l10ns={};
			var options={
				inputname:"file1",
				ff_id:t.fields.file_folder_id,
//				downscale_policy:{},
				l10ns:l10ns	
			};
			var fid=t.F("Files","user_upload_file",options);
			if (!fid) throw "Could not upload file";
			if (!fid.toString().match(/^\d+$/)) throw fid;
		}
		if (this.req.files.file.constructor==Array) {
			for (var i=0;i<this.req.files.file.length;i++) {
				this.req.files.file1=this.req.files.file[i];
				work();
			}
		} else {
			this.req.files.file1=this.req.files.file;
			work();
		}
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.move_files
	 */
	move_files: function(config) {
		var t=this;
		this.fields.ids.split(/,/).forEach(function(id) {
			var f=t.site.models.File.Get(id);
			f.MoveToFolder(t.fields.file_folder_id);
			f.SaveAll();
			// move of files and previews in filesystem is done automatically
		});
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.rotate_file
	 */
	rotate_file: function(config) {
		this.F("Files","rotate_file90",this.fields.file_id,(this.fields.dir=="right")?-1:1);
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.move_file_folders
	 */
	move_file_folders: function(config) {
		var t=this;
		this.fields.ids.split(/,/).forEach(function(id) {
			var f=t.site.models.FileFolder.Get(id);
			f.MoveToFolder(t.fields.file_folder_id);
			f.SaveAll();
			// move of directory in filesystem is done automatically
		});
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.delete_files
	 */
	delete_files: function(config) {
		var t=this;
		this.fields.ids.split(/,/).forEach(function(id) {
			var f=t.site.models.File.Get(id);
			// delete in database
			f.Delete();
			// delete files and previews in filesystem is done automatically
		});
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.delete_file_folders
	 */
	delete_file_folders: function(config) {
		var t=this;
		this.fields.ids.split(/,/).forEach(function(id) {
			var f=t.site.models.FileFolder.Get(id);
			var cnt=t.site.models.File.Count("count_of_file_folder",{file_folder_id:id});
			if (cnt) return;
			var path=t.F("Files","file_folder_path",id,1);
			// delete in database
			f.Delete();
			// delete directory in filesystem is done automatically
		});
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.reorder_files
	 */
	reorder_files: function(config) {
		var t=this;
		this.site.models.File.Reorder(this.fields.ids.split(/,/));
		return JSON.stringify({refresh:1});
	},

	/**
	 * Controller: AdminMediaLibrary.reorder_file_folders
	 */
	reorder_file_folders: function(config) {
		var t=this;
		this.site.models.FileFolder.Reorder(this.fields.ids.split(/,/));
		return JSON.stringify({refresh:1});
	}
}];

